package com.nord.Services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;

import com.nord.R;
import com.nord.Registration.Registration;
import com.nord.WebTools.HtmlBrowser;

public class NotificationBroadcastReciever extends BroadcastReceiver  {
	private List<HashMap<String, String>> eventList;
	private List<HashMap<String, String>> newsList;
	private NotificationManager nM;

	@Override
	public void onReceive(Context context, Intent intent) {
		String username = intent.getStringExtra("USERNAME");
		//Reyni að sækja lista af fréttum.
		System.out.println("intent: " + (intent != null));
		System.out.println("usr: " + username);
		String[] htmlInfo = HtmlBrowser.getExecutor(
				"http://www.nord.is/api/nord/news/?format=json&limit=2");		
		if(!htmlInfo[0].contains("Exception") && htmlInfo.length > 1){
			newsList = HtmlBrowser.jsonNewsProcessor(htmlInfo[0], context, username);
		}
		
		//sæki lista af eventum
		htmlInfo = HtmlBrowser.getExecutor(
				"http://www.nord.is/api/nord/events/?format=json&limit=10");
		if(!htmlInfo[0].contains("Exception")){
			eventList = HtmlBrowser.jsonEventProcessor(htmlInfo[0],htmlInfo[1], context);
		}
		nM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		if(newsList != null && eventList != null){
			checkNewsUpdate(context);
			checkRegNotify(context,20);
			checkWaitinglist(context,htmlInfo,username);
			
		}
	}
	
	//athugar hvort einhver skráning hefst innan minToReg mínútna.
	//ef svo er þá sendum við notification.
	private void checkRegNotify(Context context, int minToReg) {
		Notification notification;
		for (int i = 0; i != eventList.size();i++){
			long countdown = Long.parseLong(eventList.get(i).get("start"));
			String eventname = eventList.get(i).get("title");
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			
    		if(countdown <= 1000*60*minToReg && countdown > 0 && prefs.getBoolean("newsNotification", true)){    			
    			
    			Intent intent = new Intent(context, Registration.class);
    			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    			PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
    			NotificationCompat.Builder Builder = new NotificationCompat.Builder(
    					context).setContentText("Vísó Skráning hesft eftir: " + countdown/60000 + "mínútur")
    					.setContentTitle(eventname)
    					.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
    					.setContentIntent(pIntent);
    					
    			notification = Builder.build();
            	nM.notify(11, notification);
    		}
		}
	}
	//Ath hvort það sé komin ný frétt og ef svo er þá sendum við notification um það.
	private void checkNewsUpdate(Context context) {
		Notification notification;
		List<HashMap<String, String>> sqlList = new ArrayList<HashMap<String,String>>();
		
		String[] columns = new String[] { 
				"title",
				"body", 
				"date", 
				"id",
				"translation" };
		
		SQLiteAdapter sql = new SQLiteAdapter(context);
		sql.open("R");
		Cursor cursor = sql.queryTable("news", columns);
		if(cursor.getCount() != 0){
			if(cursor.moveToFirst()){
				for(int i = 0; i < cursor.getCount(); i++){
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("title", cursor.getString(cursor.getColumnIndex("title")));
					map.put("body", cursor.getString(cursor.getColumnIndex("body")));
					map.put("date", cursor.getString(cursor.getColumnIndex("date")));
					map.put("id",cursor.getString(cursor.getColumnIndex("id")));
					map.put("translation", cursor.getString(cursor.getColumnIndex("translation")));
					sqlList.add(map);
					cursor.moveToNext();
				}
			}
			else{
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("id", "empty");
				sqlList.add(map);
			}
			
			cursor.close();
			sql.close();
		}
		if(sqlList.size() > 0){
			if(Integer.parseInt(sqlList.get(0).get("id")) < Integer.parseInt(newsList.get(0).get("id"))){
				Intent intent = new Intent(context, context.getClass());
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
				NotificationCompat.Builder Builder = new NotificationCompat.Builder(
						context).setContentText("Ný frétt frá Nörd.is!")
						.setContentTitle("Ný Nörda Frétt")
						.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
						.setContentIntent(pIntent);
				notification = Builder.build();
	        	nM.notify(22, notification);
			}
		}
	}

	//Ath hvort að atburður fer að hefjast, ef svo er sendum við notification um það.
	private void checkEventStart(Context context, String serverTime) {
		//TODO- breyta gildum frá json í date hlut til að reikna tíma í event 
		//2013-03-19T23:00:00
		long eventstart = 0;
		
		for(int i = 0; i != eventList.size();i++){
			eventstart = Long.parseLong(eventList.get(i).get("start"));
			if(eventstart <= 20*1000*60){
				Notification notification;
				
			}
		}
	}
	//Ath hvort þú sért á biðlista og sendir þér notification þegar þúert ekki lengur á biðlista.
	private void checkWaitinglist(Context context,String[] htmlInfo,String username) {
		Notification notification;
		int max, current;
		if(HtmlBrowser.onList){
			for (int i = 0; i < htmlInfo.length; i++) {
				//hvað verður eventList.get("max") þegar það er ótakmarkaður fjöldi?
				max = Integer.parseInt(eventList.get(i).get("max"));
				current = 9001;
				List<HashMap<String,String>> regList = HtmlBrowser.getUsersFromJSON(htmlInfo[0], eventList.get(i).get("eventname"));
				for (int j = 0; j < htmlInfo.length; j++) {
					if (regList.get(j).get("name").matches(username)){
						current = Integer.parseInt(regList.get(j).get("position"));
					}
				}
				if(current > max)
					HtmlBrowser.onList = true;
				else{
					Intent intent = new Intent(context, context.getClass());
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
					NotificationCompat.Builder Builder = new NotificationCompat.Builder(
							context).setContentText("Ný frétt frá Nörd.is!")
							.setContentTitle("Ný Nörda Frétt")
							.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
							.setContentIntent(pIntent);
							
					notification = Builder.build();
		        	nM.notify(22, notification);
					HtmlBrowser.onList = false;
				}
			}
		}
	}
}
